package com.lanou.controller;

import com.lanou.entity.*;
import com.lanou.service.*;
import com.lanou.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("exchange")
public class ExchangeRecordController {

    @Autowired
    private UserService userService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private ExchangeRecordService exchangeRecordService;

    /**
     * 用户兑换商品
     */
    @PostMapping
    public R exchange(@RequestBody Map<String, Object> params) {
        Integer userId = Integer.valueOf(params.get("userId").toString());
        Integer goodsId = Integer.valueOf(params.get("goodsId").toString());

        User user = userService.findUserById(userId);
        Goods byId = goodsService.findById(goodsId);

        if (user == null) return R.fail("用户不存在");
        if (byId == null) return R.fail("商品不存在");

        if (user.getPoints() < byId.getPoints()) {
            return R.fail("积分不足");
        }

        // 扣除积分
        user.setPoints(user.getPoints() - byId.getPoints());
        userService.updateUser(user);

        // 保存兑换记录
        ExchangeRecord record = new ExchangeRecord();
        record.setUserId(userId);
        record.setGoodsId(goodsId);
        exchangeRecordService.addRecord(record);

        // 返回成功信息
        Map<String, Object> data = new HashMap<>();
        data.put("newPoints", user.getPoints());
        data.put("goodsName", byId.getName());
        return R.ok(data);
    }

    /**
     * 获取用户兑换记录
     */
    @GetMapping
    public R getRecords(@RequestParam Integer userId) {
        List<Map<String, Object>> recordsByUserId = exchangeRecordService.getRecordsByUserId(userId);
        return R.ok(recordsByUserId);
    }
}